{% load i18n %}
{% load static %}
{% load inventree_extras %}

// Javascript for Pricing panel
onPanelLoad('pricing', function() {
    $('#btn-update-rates').click(function() {
        inventreePut(
            '{% url "api-currency-refresh" %}',
            {},
            {
                method: 'POST',
                success: function(data) {
                    location.reload();
                }
            }
        );
    });

    $('#exchange-rate-table').inventreeTable({
        url: '{% url "api-currency-exchange" %}',
        search: false,
        showColumns: false,
        sortable: true,
        sidePagination: 'client',
        onLoadSuccess: function(response) {
            var data = response.exchange_rates || {};

            var rows = [];

            for (var currency in data) {
                rows.push({
                    'currency': currency,
                    'rate': data[currency],
                });
            }

            $('#exchange-rate-table').bootstrapTable('load', rows);
        },
        columns: [
            {
                field: 'currency',
                sortable: true,
                title: '{% trans "Currency" %}',
            },
            {
                field: 'rate',
                sortable: true,
                title: '{% trans "Rate" %}',
            }
        ]
    });
});

// Javascript for Part Category panel
onPanelLoad('category', function() {
    $('#category-select').select2({
        placeholder: '',
        width: '100%',
        ajax: {
            url: '{% url "api-part-category-list" %}',
            dataType: 'json',
            delay: 250,
            cache: false,
            data: function(params) {
                if (!params.page) {
                    offset = 0;
                } else {
                    offset = (params.page - 1) * 25;
                }

                return {
                    search: params.term,
                    offset: offset,
                    limit: 25,
                };
            },
            processResults: function(response) {
                var data = [];

                var more = false;

                if ('count' in response && 'results' in response) {
                    // Response is paginated
                    data = response.results;

                    // Any more data available?
                    if (response.next) {
                        more = true;
                    }

                } else {
                    // Non-paginated response
                    data = response;
                }

                // Each 'row' must have the 'id' attribute
                for (var idx = 0; idx < data.length; idx++) {
                    data[idx].id = data[idx].pk;
                    data[idx].text = data[idx].pathstring;
                }

                // Ref: https://select2.org/data-sources/formats
                var results = {
                    results: data,
                    pagination: {
                        more: more,
                    }
                };

                return results;
            }
        },
    });

    $('#cat-param-table').inventreeTable({
        formatNoMatches: function() { return '{% trans "No category parameter templates found" %}'; },
        columns: [
            {
                field: 'pk',
                title: 'ID',
                visible: false,
                switchable: false,
            },
            {
                field: 'parameter_template_detail.name',
                title: '{% trans "Parameter Template" %}',
                sortable: 'true',
            },
            {
                field: 'category_detail.pathstring',
                title: '{% trans "Category" %}',
            },
            {
                field: 'default_value',
                title: '{% trans "Default Value" %}',
                sortable: 'true',
                formatter: function(value, row, index, field) {
                    var bEdit = "<button title='{% trans "Edit Template" %}' class='template-edit btn btn-outline-secondary' type='button' pk='" + row.pk + "'><span class='fas fa-edit'></span></button>";
                    var bDel = "<button title='{% trans "Delete Template" %}' class='template-delete btn btn-outline-secondary' type='button' pk='" + row.pk + "'><span class='fas fa-trash-alt icon-red'></span></button>";

                    var html = value
                    html += "<div class='btn-group float-right' role='group'>" + bEdit + bDel + "</div>";

                    return html;
                }
            }
        ]
    });

    $("#cat-param-table").on('click', '.template-edit', function() {

        var category = $('#category-select').val();
        var pk = $(this).attr('pk');

        constructForm(`/api/part/category/parameters/${pk}/`, {
            fields: {
                parameter_template: {},
                category: {
                    icon: 'fa-sitemap',
                },
                default_value: {},
            },
            onSuccess: function() {
                loadTemplateTable(pk);
            }
        });
    });

    $("#cat-param-table").on('click', '.template-delete', function() {

        var category = $('#category-select').val();
        var pk = $(this).attr('pk');

        var url = `/part/category/${category}/parameters/${pk}/delete/`;

        constructForm(`/api/part/category/parameters/${pk}/`, {
            method: 'DELETE',
            title: '{% trans "Delete Category Parameter Template" %}',
            onSuccess: function() {
                loadTemplateTable(pk);
            }
        });
    });

    function loadTemplateTable(pk) {

        var query = {};

        if (pk) {
            query['category'] = pk;
        }

        // Load the parameter table
        $("#cat-param-table").bootstrapTable('refresh', {
            query: query,
            url: '{% url "api-part-category-parameter-list" %}',
        });
    }


    // Initially load table with *all* categories
    loadTemplateTable();

    $('body').on('change', '#category-select', function() {
        var pk = $(this).val();
        loadTemplateTable(pk);
    });

    $("#new-cat-param").click(function() {

        var pk = $('#category-select').val();

        constructForm('{% url "api-part-category-parameter-list" %}', {
            title: '{% trans "Create Category Parameter Template" %}',
            method: 'POST',
            fields: {
                parameter_template: {},
                category: {
                    icon: 'fa-sitemap',
                    value: pk,
                },
                default_value: {},
            },
            onSuccess: function() {
                loadTemplateTable(pk);
            }
        });
    });
});


// Javascript for the Part settings panel
onPanelLoad('parts', function() {
    $("#param-table").inventreeTable({
        url: "{% url 'api-part-parameter-template-list' %}",
        queryParams: {
            ordering: 'name',
        },
        formatNoMatches: function() { return '{% trans "No part parameter templates found" %}'; },
        columns: [
            {
                field: 'pk',
                title: '{% trans "ID" %}',
                visible: false,
                switchable: false,
            },
            {
                field: 'name',
                title: '{% trans "Name" %}',
                sortable: true,
            },
            {
                field: 'units',
                title: '{% trans "Units" %}',
                sortable: true,
                switchable: true,
            },
            {
                field: 'description',
                title: '{% trans "Description" %}',
                sortable: false,
                switchable: true,
            },
            {
                formatter: function(value, row, index, field) {
                    var bEdit = "<button title='{% trans "Edit Template" %}' class='template-edit btn btn-outline-secondary' type='button' pk='" + row.pk + "'><span class='fas fa-edit icon-green'></span></button>";
                    var bDel = "<button title='{% trans "Delete Template" %}' class='template-delete btn btn-outline-secondary' type='button' pk='" + row.pk + "'><span class='fas fa-trash-alt icon-red'></span></button>";

                    var html = "<div class='btn-group float-right' role='group'>" + bEdit + bDel + "</div>";

                    return html;
                }
            }
        ]
    });

    $("#new-param").click(function() {
        constructForm('{% url "api-part-parameter-template-list" %}', {
            fields: {
                name: {},
                units: {},
                description: {},
            },
            method: 'POST',
            title: '{% trans "Create Part Parameter Template" %}',
            refreshTable: '#param-table',
        });
    });

    $("#param-table").on('click', '.template-edit', function() {
        var button = $(this);
        var pk = button.attr('pk');

        constructForm(
            `/api/part/parameter/template/${pk}/`,
            {
                fields: {
                    name: {},
                    units: {},
                    description: {},
                },
                title: '{% trans "Edit Part Parameter Template" %}',
                refreshTable: '#param-table',
            }
        );
    });

    $("#param-table").on('click', '.template-delete', function() {
        var button = $(this);
        var pk = button.attr('pk');

        var html = `
        <div class='alert alert-block alert-danger'>
            {% trans "Any parameters which reference this template will also be deleted" %}
        </div>`;

        constructForm(
            `/api/part/parameter/template/${pk}/`,
            {
                method: 'DELETE',
                preFormContent: html,
                title: '{% trans "Delete Part Parameter Template" %}',
                refreshTable: '#param-table',
            }
        );
    });

    $("#import-part").click(function() {
        launchModalForm("{% url 'api-part-import' %}?reset", {});
    });
});


// Javascript for the Stocktake settings panel
onPanelLoad('stocktake', function() {

    {% if roles.stocktake.view %}
    var table = '#stocktake-report-table';

    var filters = loadTableFilters('stocktakereport');
    setupFilterList('stocktakereport', $(table), '#filter-list-stocktakereport');

    $(table).inventreeTable({
        url: '{% url "api-part-stocktake-report-list" %}',
        search: false,
        queryParams: filters,
        name: 'stocktakereport',
        showColumns: false,
        sidePagination: 'server',
        sortable: true,
        sortName: 'date',
        sortOrder: 'desc',
        columns: [
            {
                field: 'report',
                title: '{% trans "Report" %}',
                formatter: function(value, row) {
                    return attachmentLink(value);
                }
            },
            {
                field: 'part_count',
                title: '{% trans "Part Count" %}',
            },
            {
                field: 'date',
                title: '{% trans "Date" %}',
                sortable: true,
                formatter: function(value, row) {
                    let html = renderDate(value);

                    if (row.user_detail) {
                        html += `<span class='badge bg-dark rounded-pill float-right'>${row.user_detail.username}</span>`;
                    }

                    return html;
                }
            },
        ]
    });
    {% endif %}

    {% if roles.stocktake.add %}
    $('#btn-generate-stocktake').click(function() {
        generateStocktakeReport({
            part: {},
            category: {},
            location: {},
            generate_report: {},
            update_parts: {},
        });
    });
    {% endif %}
});
